package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.client.article.IArticleClient;
import com.heima.client.wemedia.IWemediaClient;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.AuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.admin.ApUserRealname;
import com.heima.model.common.pojos.article.ApAuthor;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.model.common.pojos.wemedia.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.AuthMapper;
import com.heima.user.service.AuthService;
import com.heima.utils.thread.AdminThreadUtil;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AuthServiceImpl extends ServiceImpl<AuthMapper, ApUserRealname> implements AuthService {

    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private AuthMapper authMapper;

    /**
     * 用户信息列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authList(AuthDto dto) {
        //1、参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数校验
        dto.checkParam();

        //2、分页查询
        Page<ApUserRealname> apUserRealnamePage = new Page<>(dto.getPage(), dto.getSize());

        //3、分页查询条件设置
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<ApUserRealname>();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        //4、开启分页查询
        Page<ApUserRealname> page = page(apUserRealnamePage, wrapper);
       /* List<ApUserRealname> apUserRealnameList = page.getRecords();
        List<ApUserRealname> list = new ArrayList<>();
        //5、添加作者姓名--从文章端远程调用获取
        //5.1遍历apUserRealnameList集合
        //5.2获取当前线程用户id
        Integer userId = ApThreadLocalUtil.get();
        System.out.println("userId = " + userId);
        for (ApUserRealname realName : apUserRealnameList) {

            ResponseResult result = articleClient.queryByUserId(userId);

            if (result.getData() != null && result.getCode() == 200) {
                Object data = result.getData();
                ApAuthor apAuthor = JSONObject.parseObject(JSON.toJSONString(data), ApAuthor.class);
                realName.setName(apAuthor.getName());
                list.add(realName);
            }
        }*/

        //6、封装数据
        PageResponseResult res = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        res.setData(page.getRecords());
        return res;
    }

    /**
     * 认证审核通过
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(AuthDto dto) {
        //1、参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2、根据id查询用户信息
        ApUserRealname apUserRealname = authMapper.selectById(dto.getId());

        if (apUserRealname == null) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //3、修改用户认证信息--审核通过
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus((short) 9);
        apUserRealname.setUpdatedTime(new Date());

        //4、更新apUserRealname数据库
        authMapper.updateById(apUserRealname);

        //5、获取ApUser用户信息,根据apUserRealname数据库查询ApUser用户信息
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserRealname.getUserId()));

        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //新建用户信息
        //6、创建自媒体账户，账号用户名密码与用户名app一致
        WmUser wmUser = new WmUser();
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setApUserId(apUser.getId());//用户id
        wmUser.setStatus((short) 9);//可用
        wmUser.setCreatedTime(new Date());

        //7、发起远程调用,在多媒体端保存用户信息
        return wemediaClient.insertUser(wmUser);

    }

    /**
     * 认证审核失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AuthDto dto) {
        //1、参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数校验
        dto.checkParam();

        //2、根据id查询用户信息
        ApUserRealname apUserRealname = authMapper.selectById(dto.getId());

        //3、修改数据库状态--用户身份审核失败
        apUserRealname.setStatus((short) 2);
        apUserRealname.setUpdatedTime(new Date());
        apUserRealname.setReason("文章内容不合规，审核不通过");//失败原因
        authMapper.updateById(apUserRealname);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
